<template>
  <div class="food-content-box restaurant-list-box">
    <el-breadcrumb separator="/" class="page-title">
      <el-breadcrumb-item :to="{ path: 'trainStation' }">Train station</el-breadcrumb-item>
      <el-breadcrumb-item>new</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="container-padding">
      <el-form :inline="true" label-position="top" :model="submitForm" size="mini" ref="submitForm" :rules="rules" v-loading="loading" class="form-min-width">
        <div class="container-box label-style">
          <el-row :gutter="20">
            <el-col>
              <el-form-item :label="$t('m.Status')" prop="status">
                <el-select  style="width: 200px" v-model="submitForm.status" placeholder="">
                  <el-option v-for="rg in status" :key="rg.value" :label="rg.text" :value="rg.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="Name_en" style="width: 200px"  prop="nameEn">
                <el-input v-model="submitForm.nameEn"></el-input>
              </el-form-item>
              <el-form-item label="Name_mm" style="width: 200px"  prop="nameMm">
                <el-input v-model="submitForm.nameMm"></el-input>
              </el-form-item>
              <el-form-item label="Township_en" style="width: 200px"  prop="townshipEn">
                <el-input v-model="submitForm.townshipEn"></el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="Township_mm" style="width: 200px"  prop="townshipMm">
                <el-input v-model="submitForm.townshipMm"></el-input>
              </el-form-item>
              <el-form-item label="Lat" style="width: 200px"  prop="lat">
                <el-input v-model="submitForm.lat"></el-input>
              </el-form-item>
              <el-form-item label="Lng" style="width: 200px"  prop="lng">
                <el-input v-model="submitForm.lng"></el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-button @click.native="cancelPutForm()" size="small" style="min-width: 85px;">
                {{$t('m.Cancel')}}
              </el-button>
              <el-button @click.native="uploadSubmitForm('submitForm')"
                         v-loading.fullscreen.lock="fullscreenLoading" size="small" style="min-width: 85px;" type="warning">
                {{$t('m.Save')}}
              </el-button>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
  import Qs from 'qs'
  import { uploadNewTrainStationFormInfo, initTrainStation } from '../../../api/mgc_api'
  export default {
    name: 'newTrainStation',
    data () {
      return {
        status: [
          {"value": 1, "text": "Active"},
          {"value": 0, "text": "Delete"},
          // {"value": 2, "text": "Suspended"},
        ],
        submitForm: {
          // 表单数据必填字段
          status: 1,
          nameMm: null,
          townshipMm: null,
          nameEn: null,
          townshipEn: null,
          lat: null,
          lng: null,
        },
        // 添加表单修改数据和字段
        id: '',
        fullscreenLoading: false,
        loading: false,
        rules: {
          status: [
            {required: true, message: 'please select', trigger: 'change'}
          ],
          nameMm: [
            {required: true, message: 'please enter', trigger: 'blur'}
          ],
          townshipMm: [
            {required: true, message: 'please enter', trigger: 'blur'}
          ],
          nameEn: [
            {required: true, message: 'please enter', trigger: 'blur'}
          ],
          townshipEn: [
            {required: true, message: 'please enter', trigger: 'blur'}
          ],
          lat: [
            {
              validator: (rule, value, callback) => {
                if (/^(\-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/.test(value) == false) {
                  callback(new Error('Please fill in the correct latitude'))
                } else {
                  callback()
                }
              }, trigger: 'blur'
            },
            {required: true, message: 'please enter', trigger: 'blur'}
          ],
          lng: [
            {
              validator: (rule, value, callback) => {
                if (/^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/.test(value) == false) {
                  callback(new Error('Please fill in the correct longitude'))
                } else {
                  callback()
                }
              }, trigger: 'blur'
            },
            {required: true, message: 'please enter', trigger: 'blur'}
          ],
        }
      }
    },
    methods: {
      // message alert 用于前端错误提示信息
      messageToastErr (msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 1500,
          type: 'error'
        })
      },
      messageToastSuccess (msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 1500,
          type: 'success'
        })
      },
      cancelPutForm () {
        // if (this.id) {
        //   this.initForm()
        // } else {
        //   this.removeAgentForm ('submitForm')
        // }
        this.$router.go(-1)
      },
      // 表单信息上传
      uploadSubmitForm (submitForm) {
        this.$refs[submitForm].validate((valid) => {
          if (valid){
            console.log(valid)
            // 有id -- 则提交编辑信息
            if (this.id) {
              let formAjaxData = {
                /* 编辑时添加的字段 start */
                id: this.id,
                /* 编辑时添加的字段 end */
                status: this.submitForm.status,
                nameMm: this.submitForm.nameMm,
                townshipMm: this.submitForm.townshipMm,
                nameEn: this.submitForm.nameEn,
                townshipEn: this.submitForm.townshipEn,
                lat: this.submitForm.lat,
                lng: this.submitForm.lng,
              }
              let params = Qs.stringify(formAjaxData)
              console.log(params, 'params')
              let config = {
                'Content-Type': 'multipart/form-data'
              }
              this.fullscreenLoading = true
              uploadNewTrainStationFormInfo(params, config)
                .then((res) => {
                  if (res) {
                    if (res.data) {
                      console.log(res)
                      if (res.data.errorID == 0) {
                        this.messageToastSuccess('success')
                        this.initForm()
                        this.$router.push('/trainStation')
                        this.fullscreenLoading = false
                      }
                    }
                  }
                })
                .catch((error) => {
                  console.log(error)
                  this.fullscreenLoading = false
                  this.messageToastErr('error,please try again leter')
                })
            } else {
              //新增 -- 表单信息
              let formAjaxData = {
                status: this.submitForm.status,
                nameMm: this.submitForm.nameMm,
                townshipMm: this.submitForm.townshipMm,
                nameEn: this.submitForm.nameEn,
                townshipEn: this.submitForm.townshipEn,
                lat: this.submitForm.lat,
                lng: this.submitForm.lng,
              }
              let params = Qs.stringify(formAjaxData)
              let config = {
                'Content-Type': 'multipart/form-data'
              }
              this.fullscreenLoading = true
              uploadNewTrainStationFormInfo(params, config)
                .then((res) => {
                  if (res) {
                    if (res.data) {
                      console.log(res)
                      if (res.data) {
                        console.log(res)
                        if (res.data.errorID == 0) {
                          this.messageToastSuccess('success')
                          this.$refs[submitForm].resetFields()
                          this.$router.push('/trainStation')
                          this.fullscreenLoading = false
                        }
                      }
                    }
                  }
                })
                .catch((error) => {
                  console.log(error)
                  this.fullscreenLoading = false
                  this.messageToastErr('error,please try again leter')
                })
            }
          } else {
            this.messageToastErr('error submit!!')
            return false
          }
        })
      },
      // 初始化 Bus Line 表单
      initForm () {
        this.loading = true
        initTrainStation(this.id).then((res) => {
          if (res.data) {
            console.log(res.data)
            this.submitForm.status = res.data.status
            this.submitForm.nameMm = res.data.nameMm
            this.submitForm.townshipMm = res.data.townshipMm
            this.submitForm.nameEn = res.data.nameEn
            this.submitForm.townshipEn = res.data.townshipEn
            this.submitForm.lat = res.data.lat
            this.submitForm.lng = res.data.lng
            this.loading = false
          }
        }).catch((error) => {
          if (error.response) {
            // 请求已经发出，但是服务器响应返回的状态吗不在2xx的范围内
            console.log(error.response.data)
            console.log(error.response.status)
            console.log(error.response.header)
          } else {
            // 一些错误是在设置请求的时候触发
            console.log('Error', error.message)
          }
          console.log(error.config)
          this.loading = false
          this.messageToastErr('error,please refresh the page later')
        })
      },
    },
    mounted () {
      this.id = this.$route.query.id || ''
      if (this.id) {
        this.initForm()
      }
    }
  }
</script>
<style>
  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px;
  }
  .food-content-box .container-padding {
    padding: 20px 40px 0 40px;
  }
  .list-notes{
    text-align: center;
    display: block;
  }
</style>
